package com.vr.cloudpicture.manager.websocket.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.vr.cloudpicture.manager.websocket.model.PictureEditEvent;
import com.vr.cloudpicture.manager.websocket.model.PictureEditRequestMessage;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;

/**
 * 图片编辑事件消息生产者
 *
 * @author hzh
 * @date 2025/05/28
 */
@Slf4j
@Component
@AllArgsConstructor
public class PictureEditEventProducer {
    private final Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    public void publishEvent(PictureEditRequestMessage requestMessage, WebSocketSession session, UserLogin user, Long pictureId) {
        // 拿到无锁环形队列
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        // 获取可以生成的位置
        long next = ringBuffer.next();
        // 给事件存放数据
        PictureEditEvent pictureEditEvent = ringBuffer.get(next);
        pictureEditEvent.setPictureEditRequestMessage(requestMessage);
        pictureEditEvent.setSession(session);
        pictureEditEvent.setUser(user);
        pictureEditEvent.setPictureId(pictureId);
        // 发布消息
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机(会等待正在处理的消息处理完再停机)
     */
    @PreDestroy
    public void close() {
        pictureEditEventDisruptor.shutdown();
    }
}
